// static/js/course_mgmt.js

// 全局状态
let courses = [];
let editingId = null;
let adding = false;

// DOM 引用
const msgEl   = document.getElementById('courseMgmtMsg');
const tbody   = document.getElementById('course-tbody');
const addBtn  = document.getElementById('add-course-btn');

// 组件挂载：弹窗打开时加载列表
document.getElementById('courseMgmtModal')
  .addEventListener('show.bs.modal', async () => {
    msgEl.style.display = 'none';
    adding = false;
    editingId = null;
    addBtn.disabled = false;
    await loadCourses();
  });

/**
 * 从后端拉取课程列表并渲染
 */
async function loadCourses() {
  try {
    const res = await fetch('/api/courses');
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    courses = await res.json();
    renderCourses();
  } catch (err) {
    showMsg('加载失败：' + err.message);
    console.error(err);
  }
}

/**
 * 绑定 blur 校验动画
 */
function bindBlurValidation(inputEl, validateFn) {
  inputEl.addEventListener('blur', () => {
    const val = inputEl.value.trim();
    if (!validateFn(val)) {
      inputEl.classList.add('input-invalid');
      inputEl.addEventListener('animationend', () => {
        inputEl.classList.remove('input-invalid');
      }, { once: true });
    }
  });
}

/**
 * 渲染表格行：普通行、新增行、编辑行
 */
function renderCourses() {
  tbody.innerHTML = '';

  // 普通行
  courses.forEach(c => {
    if (editingId === c.id) return;  // 编辑行后渲染
    const disabled = (adding || editingId !== null) ? 'disabled' : '';
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td class="align-middle text-center">
        <span class="course-name" data-bs-toggle="tooltip"
              title="${c.name.replace(/"/g,'&quot;')}">
          ${c.name}
        </span>
      </td>
      <td class="text-center">
        <button class="btn btn-sm btn-outline-secondary me-1" title="上移"
                onclick="moveCourse(${c.id},'up')" ${disabled}>
          <i class="bi bi-arrow-up"></i>
        </button>
        <button class="btn btn-sm btn-outline-secondary me-1" title="下移"
                onclick="moveCourse(${c.id},'down')" ${disabled}>
          <i class="bi bi-arrow-down"></i>
        </button>
        <button class="btn btn-sm btn-outline-info me-1" title="编辑"
                onclick="enterEditMode(${c.id})" ${disabled}>
          <i class="bi bi-pencil-fill"></i>
        </button>
        <button class="btn btn-sm btn-outline-danger" title="删除"
                onclick="deleteCourse(${c.id})" ${disabled}>
          <i class="bi bi-trash-fill"></i>
        </button>
      </td>
    `;
    tbody.appendChild(tr);
  });

  // 新增模式行
  if (adding) {
    const trNew = document.createElement('tr');
    trNew.id = 'new-course-row';
    trNew.innerHTML = `
      <td class="align-middle text-center">
        <input type="text"
               id="new-course-input"
               class="form-control form-control-sm text-center"
               value="">
      </td>
      <td class="text-center">
        <button class="btn btn-sm btn-outline-success me-1"
                title="保存" onclick="saveNewCourse()">
          <i class="bi bi-check-lg"></i>
        </button>
        <button class="btn btn-sm btn-outline-secondary"
                title="取消" onclick="cancelNewCourse()">
          <i class="bi bi-x-lg"></i>
        </button>
      </td>
    `;
    tbody.appendChild(trNew);
    const newInput = document.getElementById('new-course-input');
    newInput.focus();
    bindBlurValidation(newInput, name =>
      name !== '' && !courses.some(c => c.name === name)
    );
  }

  // 编辑模式行
  if (editingId !== null) {
    const c = courses.find(x => x.id === editingId);
    const trEdit = document.createElement('tr');
    trEdit.id = 'edit-course-row';
    trEdit.innerHTML = `
      <td class="align-middle text-center">
        <input type="text"
               id="edit-course-input"
               class="form-control form-control-sm text-center"
               value="${c.name.replace(/"/g,'&quot;')}">
      </td>
      <td class="text-center">
        <button class="btn btn-sm btn-outline-success me-1"
                title="保存" onclick="saveCourse(${c.id})">
          <i class="bi bi-check-lg"></i>
        </button>
        <button class="btn btn-sm btn-outline-secondary"
                title="取消" onclick="cancelEdit()">
          <i class="bi bi-x-lg"></i>
        </button>
      </td>
    `;
    // 插入到对应位置
    const idx = courses.findIndex(x => x.id === editingId);
    const rows = Array.from(tbody.children);
    if (rows.length === 0 || idx >= rows.length) {
      tbody.appendChild(trEdit);
    } else {
      tbody.insertBefore(trEdit, rows[idx]);
    }
    const editInput = document.getElementById('edit-course-input');
    editInput.focus();
    bindBlurValidation(editInput, name =>
      name !== '' && !courses.some(c => c.name === name && c.id !== editingId)
    );
  }

  // 初始化所有 Tooltip
  const tipList = [].slice.call(
    tbody.querySelectorAll('[data-bs-toggle="tooltip"]')
  );
  tipList.forEach(el => new bootstrap.Tooltip(el));
}

// 进入添加模式
addBtn.addEventListener('click', () => {
  if (adding || editingId !== null) return;
  adding = true;
  addBtn.disabled = true;
  renderCourses();
});

// 取消新增
function cancelNewCourse() {
  adding = false;
  addBtn.disabled = false;
  renderCourses();
}

// 保存新增
async function saveNewCourse() {
  const input = document.getElementById('new-course-input');
  const name = input.value.trim();
  if (!name) return showMsg('课程名不能为空');
  if (courses.some(c => c.name === name)) return showMsg('课程名已存在');
  try {
    const res = await fetch('/api/courses', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({name})
    });
    const text = await res.text();
    const payload = JSON.parse(text);
    if (!res.ok) throw new Error(payload.error || payload.message || text);
    adding = false;
    addBtn.disabled = false;
    await loadCourses();
  } catch (err) {
    showMsg(err.message);
  }
}

// 进入编辑模式
function enterEditMode(id) {
  if (adding || editingId !== null) return;
  editingId = id;
  addBtn.disabled = true;
  renderCourses();
}

// 取消编辑
function cancelEdit() {
  editingId = null;
  addBtn.disabled = false;
  renderCourses();
}

// 保存编辑
async function saveCourse(id) {
  const input = document.getElementById('edit-course-input');
  const name = input.value.trim();
  if (!name) return showMsg('课程名不能为空');
  if (courses.some(c => c.name === name && c.id !== id)) return showMsg('课程名已存在');
  try {
    const res = await fetch(`/api/courses/${id}`, {
      method: 'PUT',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({name})
    });
    const text = await res.text();
    const payload = JSON.parse(text);
    if (!res.ok) throw new Error(payload.error || payload.message || text);
    editingId = null;
    addBtn.disabled = false;
    await loadCourses();
  } catch (err) {
    showMsg(err.message);
  }
}

// 删除课程（直接删除，无确认）
async function deleteCourse(id) {
  try {
    const res = await fetch(`/api/courses/${id}`, { method: 'DELETE' });
    const text = await res.text();
    let payload;
    try { payload = JSON.parse(text); } catch {}
    if (!res.ok) throw new Error(payload?.error || payload?.message || text);
    await loadCourses();
  } catch (err) {
    showMsg('删除失败：' + err.message);
  }
}

// 上移/下移课程
async function moveCourse(id, dir) {
  try {
    await fetch(`/api/courses/${id}/move`, {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({dir})
    });
    await loadCourses();
  } catch (err) {
    showMsg('移动失败：' + err.message);
  }
}

// 全局错误提示函数
function showMsg(msg) {
  msgEl.textContent = msg;
  msgEl.style.display = 'inline';
  setTimeout(() => { msgEl.style.display = 'none'; }, 3000);
}
